/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package iconeLibrary.view;

import iconeLibrary.controler.TypeImage;
import iconeLibrary.model.*;
import iconeLibrary.controler.Controler;
import iconeLibrary.controler.ErrorsType;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.apache.batik.transcoder.TranscoderException;
import org.xmldb.api.base.XMLDBException;

/**
 *
 * @author Ayede Sonia :: Gaudino Anthony :: Herche Bilal :: Teixeira Tiago :: Touati Samed  :: Wadjahdi Marc
 */
public class IconeLibraryServlet extends HttpServlet {

    private static final long serialVersionUID = 4726581784877047255L;
    private Controler controler;
    private String URL;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response, boolean isGet)
            throws ServletException, IOException {

        ServletOutputStream out = null;

        try {

            controler = new Controler();

            controler.createIcon(URL);

            if (isGet) {
                String typeImage = controler.getParams().get("typeImage").get(0);
                response.setContentType("image/" + typeImage);
                out = response.getOutputStream();
                try {
                    controler.DocumentToImage(controler.getDocumentFinal(), TypeImage.valueOf(typeImage), out);
                } catch (IOException ex) {
                    request.getSession().setAttribute("errorName", ErrorsType.IOError);
                    RequestDispatcher requestDispatcher = request.getRequestDispatcher("ErrorServlet");
                    requestDispatcher.forward(request, response);
                } catch (TranscoderException ex) {
                    request.getSession().setAttribute("errorName", ErrorsType.ErrorConvertImage);
                    RequestDispatcher requestDispatcher = request.getRequestDispatcher("ErrorServlet");
                    requestDispatcher.forward(request, response);
                }
            } else {
                response.setContentType("application/xhtml+xml;charset=UTF-8");
                out = response.getOutputStream();
                printResult(out, controler.getFinalIconName(), request);
            }

        } catch (XMLDBException ex) {
            request.getSession().setAttribute("errorName", ErrorsType.ErrorBD);
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("ErrorServlet");
            requestDispatcher.forward(request, response);

        } catch (IOException ex) {
            request.getSession().setAttribute("errorName", ErrorsType.IOError);
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("ErrorServlet");
            requestDispatcher.forward(request, response);
        } finally {
            controler.getConnection().closeConnection();
            if (out != null) {
                out.close();
            }
        }
    }

    /**
     * Method that print the result .
     */
    private void printResult(ServletOutputStream out, String imageName, HttpServletRequest request) {
        try {
            String url = request.getRequestURL() + "?query_url=" + URL;
            out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"");
            out.println("\"DTD/xhtml1-strict.dtd\">");
            out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
            out.println("<head>");
            out.println("<title>" + imageName + "</title>");
            out.println(" <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />");
            out.println("<link href=\"iconLibrary.css\" rel=\"stylesheet\" type=\"text/css\" />");
            out.println("</head>");
            out.println("<body>");
            out.println("<div id=\"wrapper\">");
            out.println("<div id=\"top-menu\">");
            out.println("<div id=\"account\">");
            out.println("</div>");
            out.println("</div>");
            out.println("<div id=\"header\">");
            out.println("<h1>Projet Icone Library</h1>");
            out.println("</div>");
            out.println("<br></br>");
            out.println("<br></br>");
            out.println("<br></br>");
            out.println("<div id=\"content\">");
            out.println("<br></br>");
            controler.serialisation(controler.getDocumentFinal(), out);
            out.println("<br></br>");
            out.println("<br></br>");
            out.println("<p> Use this url to generate this icon : ");
            out.print("<a href=\"");
            out.println(url + "\">" + url + "</a></p>");
            out.println("</div>");
            out.println("<br></br>");
            out.println("<br></br>");
            out.println("<br></br>");
            out.println("<div id=\"footer\">");
            out.println("M1 Info Nice - 2009/2010 - Ayede Sonia :: Gaudino Anthony :: Herche Bilal :: Teixeira Tiago :: Touati Samed  :: Wadjahdi Marc");
            out.println("</div>");
            out.println("</div>");
            out.println("</body>");
            out.println("</html>");
        } catch (IOException ex) {
            Logger.getLogger(IconeLibraryServlet.class.getName()).log(Level.SEVERE, null, ex);
            request.getSession().setAttribute("errorName", ErrorsType.IOError);
        }catch(TransformerConfigurationException ex){
            request.getSession().setAttribute("errorName", ErrorsType.ErrorTransformer);
        }catch(TransformerException ex){
            request.getSession().setAttribute("errorName", ErrorsType.ErrorTransformer);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        URL = request.getParameter("query_url");
        processRequest(request, response, true);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("mainImageName");
        String size = request.getParameter("mainImageSize");

        String[] names = request.getParameterValues("imagesNames[]");
        String[] sizes = request.getParameterValues("imagesSizes[]");
        String[] offsetsX = request.getParameterValues("imagesOffsetsX[]");
        String[] offsetsY = request.getParameterValues("imagesOffsetsY[]");

        String filter = request.getParameter("filter");

        String type = request.getParameter("type");

        String newName = request.getParameter("nomNouvelIcone");

        URL = name + "/" + size + "/0/0/";

        if (sizes != null) {
            for (int i = 0; i < sizes.length; i++) {
                URL += "combine/" + names[i] + "/" +
                        (Float.parseFloat(sizes[i]) / 100) + "/" +
                        offsetsX[i] + "/" + offsetsY[i] + "/";

            }
        }

        if (!filter.equalsIgnoreCase("none")) {
            URL += "filtre/" + filter + "/";
        }

        URL += newName + "/" + type;

        processRequest(request, response, false);

    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
